package com.jjw.springbootcvs.controller;


import com.jjw.springbootcvs.config.BootCvsProperties;
import com.jjw.springbootcvs.pojo.entity.SysRole;
import com.jjw.springbootcvs.pojo.entity.SysUser;
import com.jjw.springbootcvs.service.RoleService;
import com.jjw.springbootcvs.utils.Result;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiaojuan
 * @Date 2024/11/4
 * @Description
 */
@Controller
@RequestMapping("/sys/role/")
@RequiredArgsConstructor
public class RoleController {

    private final RoleService roleService;

    private final BootCvsProperties bootCvsProperties;
    /**
     * 角色列表
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String list(Model model){
        List<SysRole> sysRoles = roleService.getAllRoleList();
        model.addAttribute("roleList",sysRoles);
        return "sysRole/list";
    }

    @PostMapping("/add")
    public String add(SysRole sysRole, HttpSession session){
        SysUser user = (SysUser) session.getAttribute(bootCvsProperties.getSessionKey());
        sysRole.setCreatedUserId(user.getId());
        sysRole.setUpdatedUserId(user.getId());
        roleService.add(sysRole);
        return "redirect:/sys/role/list";
    }

    /**
     * 根据id查询角色code是否存在存在抛异常
     * @param roleCode
     * @return
     */
    @GetMapping("/codeExist")
    @ResponseBody
    public Result codeExist(String roleCode){
        SysRole sysRole = roleService.getRoleByCode(roleCode);
        return Result.success();
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Result delete(@PathVariable("id") Long id){
        roleService.delete(id);
        return Result.success();
    }

    /**
     * 根据id查询信息
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/toUpdate/{id}")
    public String update(@PathVariable("id") Long id, Model model){
        SysRole sysRole = roleService.getRoleById(id);
        model.addAttribute("sysRole",sysRole);
        return "sysRole/update";
    }

    /**
     * 修改角色信息
     * @param sysRole
     * @param session
     * @return
     */
    @PostMapping("/update")
    public String update(SysRole sysRole, HttpSession session){
        SysUser user = (SysUser) session.getAttribute(bootCvsProperties.getSessionKey());
        sysRole.setUpdatedUserId(user.getId());
        roleService.update(sysRole);
        return "redirect:/sys/role/list";
    }



}
